package com.example.psychologicalappointmentsystem.tools;

import com.example.psychologicalappointmentsystem.Entity.User;
import com.example.psychologicalappointmentsystem.JpaRepository.UserRepository;
import com.example.psychologicalappointmentsystem.config.web.WebInterceptor;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

@Slf4j
public class JWTFilter extends OncePerRequestFilter {

    @Autowired
    private JWTUtils jwtUtils;

    @Autowired
    private UserRepository userRepository;


    @Override
    protected void doFilterInternal(HttpServletRequest request, javax.servlet.http.HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String url = request.getRequestURL().toString();
        String path = request.getServletPath();
        String token = request.getHeader("Authorization");
        System.out.println(url);
        // 从请求头中获取Authorization
        if (url.contains("/user/login")||url.contains("/user/register")){
            System.out.println(token);
        } else if (WebInterceptor.excludeUrls.contains(path)) {
            log.info("接口->{},跳过权限拦截",path);
        }else if (path.startsWith("/ws/chat")){
            log.info("接口->{},跳过权限拦截",path);
        } else {
            String jwtToken = token.substring(7); // 去掉 "Bearer " 前缀
            if (token != null && jwtUtils.validateToken(jwtToken)) {
                // 解析JWT并获取用户信息
                String username = jwtUtils.getUsernameFromToken(jwtToken);

                User user = userRepository.findByUsername(username);
                List<GrantedAuthority> authorities = new ArrayList<>();
                authorities.add(new SimpleGrantedAuthority(user.getRole().name()));

                // 设置当前用户信息到上下文
                SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(user, null, authorities));
            }
        }
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {
    }
}

